package com.example.project3.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @ClassName Encryption .java
 * @Description 这个类提供一些加密的方法，比如MD5签名等等。
 * @Author LiuJinyu
 * @Date 2023/5/26 17:19
 * @Version 1.0
 */
@Slf4j
@Component
public class Encryption {
    private static final String SALT = "24_qi,3_bu,di_4_zu@stx.666.xxx87ojbhghj";

    /**
     * 传入一个原字符串获得哈希计算出的字节流。
     *
     * @param origin
     * @return
     */
    public byte[] MD5(String origin) {
        MessageDigest md = null;
        byte[] result = null;
        try {
            md = MessageDigest.getInstance("MD5");
            // 反复调用update输入数据:
            md.update(origin.getBytes(StandardCharsets.UTF_8));
            md.update(SALT.getBytes(StandardCharsets.UTF_8));
            result = md.digest();
        } catch (NoSuchAlgorithmException e) {
            log.warn("MD5生成错误", e);
            e.printStackTrace();
            result = new byte[]{123, 31, 32, 45, 31, 32, 45, 53, 13, 42, 124, 6, 74, 24, 3, 67, 1, 1, 3, 5, 23, 32, 46, 1, 3, 23, 4, 6, 45, 23, 4, 34, 43};
        }
        return result;
    }

    public String str(byte[] bytes, int length) {
        StringBuffer result = new StringBuffer(new BigInteger(1, bytes).toString(8));
        //获取的字符串不足32位的用“0”补齐
        for (int i = 0; i < length - result.length(); i++) {
            result.append("0");
        }
        if (result.length() > length) {
            return result.substring(0, length);
        }
        return result.toString();
    }
}
